package com.example.dingding.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkworkflow_1_0.Client;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceHeaders;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceRequest;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.example.dingding.config.HttpHelper;
import com.example.dingding.entity.UseCar;
import com.example.dingding.entity.dto.UseCarSmsDTO;
import com.example.dingding.mapper.UseCarMapper;
import com.example.dingding.service.SmsService;
import com.example.dingding.service.UseCarService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.NullValueInNestedPathException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * @author cgyt
 * @date 2024/4/19 14:24
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {



    @Value("${ums86.url}")
    private String url;

    @Autowired
    private UseCarMapper useCarMapper;

    @Autowired
    HttpHelper httpHelper = new HttpHelper();

    @Override
    public String sendMessage(UseCarSmsDTO useCarSmsDTO) {
        String info = null;
        try {
            HttpClient httpclient = new HttpClient();
            PostMethod post = new PostMethod(url);
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
            post.addParameter("SpCode", useCarSmsDTO.getSpCode());
            post.addParameter("LoginName", useCarSmsDTO.getLoginName());
            post.addParameter("Password", useCarSmsDTO.getPassword());
            post.addParameter("MessageContent", useCarSmsDTO.getMessageContent());
            post.addParameter("TemplateId", useCarSmsDTO.getTemplateId());
            post.addParameter("UserNumber", useCarSmsDTO.getUserNumber());
            post.addParameter("SerialNumber", useCarSmsDTO.getSerialNumber());
            post.addParameter("f", useCarSmsDTO.getF());
            httpclient.executeMethod(post);
            info = new String(post.getResponseBody(), "gbk");
            log.info("info:{}", info);
            return info;
        } catch (NullValueInNestedPathException e) {
            e.printStackTrace();
            return "发送失败";
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public UseCar carMessage(String instanceId) {
        String access_token = httpHelper.getAccess_Token();

        UseCar useCarSmsDTO=new UseCar();

        Client client = null;
        try {
            client = createClient();
        } catch (Exception e) {
            e.printStackTrace();
        }

        GetProcessInstanceHeaders getProcessInstanceHeaders = new GetProcessInstanceHeaders();
        getProcessInstanceHeaders.xAcsDingtalkAccessToken = access_token;
        GetProcessInstanceRequest getProcessInstanceRequest = new GetProcessInstanceRequest()
                .setProcessInstanceId(instanceId);
        try {
            GetProcessInstanceResponse processInstanceWithOptions = client.getProcessInstanceWithOptions(getProcessInstanceRequest, getProcessInstanceHeaders, new RuntimeOptions());
            int type=useCarMapper.selectApprovalType(instanceId);
            String carMessage=null;
            String carNumber=null;
            String currentMileage=null;
            String expenses=null;
            String originalMileage=null;
            String kilometers=null;
            if (type==0){
                carMessage=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(16).getValue());
                carNumber=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(18).getValue());
                currentMileage=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(21).getValue());
                expenses=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(17).getValue());
                originalMileage=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(20).getValue());
                kilometers=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(19).getValue());
            }else {
                carMessage=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(13).getValue());
                carNumber=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(13).getValue());
                currentMileage=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(18).getValue());
                originalMileage=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(17).getValue());
                kilometers=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(16).getValue());

            }
            String useCarTime=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(10).getValue());
            String startPoint=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(13).getValue());
            String specificDestination=JSON.toJSONString(processInstanceWithOptions.getBody().getResult().getFormComponentValues().get(7).getValue());

//            carMessage = carMessage.substring(1, carNumber.length() - 1);
//            carNumber = carNumber.substring(1, carNumber.length() - 1);
//            useCarTime = useCarTime.substring(1, useCarTime.length() - 1);
//            startPoint = startPoint.substring(1, startPoint.length() - 1);
//            specificDestination = specificDestination.substring(1, specificDestination.length() - 1);


            useCarSmsDTO.setCarMessage(carMessage);
            useCarSmsDTO.setCarNumber(carNumber);
            useCarSmsDTO.setUseTime(useCarTime);
            useCarSmsDTO.setStartingPoint(startPoint);
            useCarSmsDTO.setSpecificDestination(specificDestination);
            useCarSmsDTO.setCurrentMileage(currentMileage);
            useCarSmsDTO.setOriginalMileage(originalMileage);
            useCarSmsDTO.setKilometers(kilometers);
            useCarSmsDTO.setExpenses(expenses);


        } catch (TeaException err) {
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!Common.empty(err.code) && !Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }
        return useCarSmsDTO;
    }

    @Override
    public Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkworkflow_1_0.Client(config);
    }

    @Override
    public String sSerialNumber() {
        // 创建Random对象
        Random random = new Random();

        // 用于存储20位数字的字符串
        StringBuilder sb = new StringBuilder(20);

        //生成20位随机数字
        for (int i = 0; i < 20; i++) {
            // 生成0-9之间的随机整数
            int digit = random.nextInt(10);
            // 添加到字符串中
            sb.append(digit);
        }

        // 将StringBuilder转换为String
        String randomNumber = sb.toString();

        // 打印随机生成的20位数字
        System.out.println("随机生成的20位数字: " + randomNumber);
        return randomNumber;
    }


}
